//------------------------------------------------------------------------------
// Copyright (c) 2008 www.dnaide.com
// Licensed under the MIT (MIT-LICENSE.txt)
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;

namespace DNAide.Web
{
	internal class ViewStateFilter : Stream
	{
		private Stream _sink;

		#region Properites

		public override bool CanRead
		{
			get { return true; }
		}

		public override bool CanSeek
		{
			get { return true; }
		}

		public override bool CanWrite
		{
			get { return true; }
		}

		public override void Flush()
		{
			_sink.Flush();
		}

		public override long Length
		{
			get { return 0; }
		}

		private long _position;
		public override long Position
		{
			get { return _position; }
			set { _position = value; }
		}

		#endregion


		public ViewStateFilter(Stream sink)
    {
      _sink = sink;
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
      return _sink.Read(buffer, offset, count);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
      return _sink.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
      _sink.SetLength(value);
    }

    public override void Close()
    {
      _sink.Close();
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
      byte[] data = new byte[count];
      Buffer.BlockCopy(buffer, offset, data, 0, count);
      string html = System.Text.Encoding.Default.GetString(buffer);

      int startPoint = html.IndexOf("<div>\r\n<input type=\"hidden\" name=\"__VIEWSTATE\"");
			if (startPoint >= 0)
			{
				int endPoint = html.IndexOf("/>\r\n</div>", startPoint) + 10;
				string viewstateInput = "\r\n" + html.Substring(startPoint, endPoint - startPoint) + "\r\n";
				html = html.Remove(startPoint, endPoint - startPoint);
				int formEndStart = html.IndexOf("</form>");
				if (formEndStart >= 0)
				{
					html = html.Insert(formEndStart, viewstateInput);
				}
			}
			else
			{
				startPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\"");
				if (startPoint >= 0)
				{
					int endPoint = html.IndexOf("/>", startPoint) + 2;
					string viewstateInput = "\r\n" + html.Substring(startPoint, endPoint - startPoint) + "\r\n";
					html = html.Remove(startPoint, endPoint - startPoint);
					int formEndStart = html.IndexOf("</form>");
					if (formEndStart >= 0)
					{
						html = html.Insert(formEndStart, viewstateInput);
					}
				}
			}

      byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
      _sink.Write(outdata, 0, outdata.GetLength(0));
    }
	}
}
